package com.yxsk.relay.job.admin.web.controller;

import com.yxsk.relay.job.admin.web.common.config.properties.WebConfigProperties;
import com.yxsk.relay.job.admin.web.common.enums.ResultEnum;
import com.yxsk.relay.job.admin.web.common.exception.AdminLoginRuntimeException;
import com.yxsk.relay.job.admin.web.common.utils.EncryptUtil;
import com.yxsk.relay.job.admin.web.common.utils.JwtUtil;
import com.yxsk.relay.job.admin.web.entity.User;
import com.yxsk.relay.job.admin.web.service.UserService;
import com.yxsk.relay.job.component.common.protocol.message.base.ResultResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 小懒虫
 * @date 2018/8/14
 */
@Controller
public class LoginController {

    @Autowired
    private WebConfigProperties webConfigProperties;

    @Autowired
    private UserService userService;

    /**
     * 跳转到登录页面
     */
    @GetMapping("/login")
    public String toLogin(Model model) {
        model.addAttribute("isCaptcha", webConfigProperties.isCaptchaOpen());
        return "/login";
    }

    /**
     * 实现登录
     */
    @PostMapping("/login")
    @ResponseBody
    public ResultResponse login(String username, String password, String captcha, HttpServletRequest request) {
        // 判断账号密码是否为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            throw new AdminLoginRuntimeException(ResultEnum.USER_NAME_PWD_NULL);
        }
        User user = this.userService.findByUsername(username);
        if (user == null) {
            throw new AdminLoginRuntimeException(ResultEnum.USER_NOT_FOUND);
        }
        // 加密校验
        String encrypt = EncryptUtil.encrypt(password, user.getSalt());
        if (!user.getPassword().equals(encrypt)) {
            throw new AdminLoginRuntimeException(ResultEnum.PASSWORD_ERROR);
        }

        // 生成token
        String token = JwtUtil.getToken(user.getId(), user.getPassword(), webConfigProperties.getLoginEffectiveDays());

        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("url", "/");
        responseMap.put("token", token);
        responseMap.put("tokenHeaderName", JwtUtil.TOKEN_NAME_OF_COOKIE);
        responseMap.put("effectiveDays", this.webConfigProperties.getLoginEffectiveDays());
        return ResultResponse.ok("登录成功", responseMap);
    }

    /**
     * 验证码图片
     */
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置响应头信息，通知浏览器不要缓存
        response.setHeader("Expires", "-1");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "-1");
        response.setContentType("image/jpeg");

        // 获取验证码
        //   String code = CaptchaUtil.getRandomCode();
        // 将验证码输入到session中，用来验证
        //   request.getSession().setAttribute("captcha", code);
        // 输出到web页面
        //   ImageIO.write(CaptchaUtil.genCaptcha(code), "jpg", response.getOutputStream());
    }

    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public String logout() {
        //   SecurityUtils.getSubject().logout();
        return "redirect:/login";
    }

    /**
     * 权限不足页面
     */
    @GetMapping("/noAuth")
    public String noAuth() {
        return "/system/main/noAuth";
    }

    /**
     * 处理错误页面
     */
    /*@RequestMapping("/error")
    public String handleError(Model model, HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String errorMsg = "好像出错了呢！";
        if (statusCode == 404) {
            errorMsg = "页面找不到了！好像是去火星了~";
        }

        model.addAttribute("statusCode", statusCode);
        model.addAttribute("msg", errorMsg);
        return "/system/main/error";
    }*/
}
